package com.portal4kids.controller;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.portal4kids.model.Holidays;
import com.portal4kids.model.Places;
import com.portal4kids.util.HibernateUtil;

public class HolidaysManager extends HibernateUtil{
	
	public Holidays saveHoliday(Holidays holiday){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		holiday.setAvarage(0);
		holiday.setNumberOfVotes(0);
		holiday.setRating(0);
		holiday.setComments("");
		session.save(holiday);
		session.getTransaction().commit();
		return holiday;
	}
	
	public List<Holidays> getHolidaysFromDB(String type){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Holidays> holidayList = new ArrayList<Holidays>();
		Query q = session.createQuery("from Holidays where type='" + type + "'");
		holidayList = q.list();
		session.getTransaction().commit();
		return holidayList;
	}
	
	public List<Holidays> getHolidaysAfterId(int id){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Holidays> holidayList = new ArrayList<Holidays>();
		Query q = session.createQuery("from Holidays where id_holidays=" + id);
		holidayList = q.list();
		session.getTransaction().commit();
		return holidayList;
	}
	
	public static void addRank(int id_place, int rank){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Holidays holiday = (Holidays) session.load(Holidays.class, id_place);
		
//		DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance();
//		symbols.setDecimalSeparator('.');
//		DecimalFormat df = new DecimalFormat("#.##", symbols);
		
		int numberOfVotes = holiday.getNumberOfVotes();
		numberOfVotes++;
		holiday.setNumberOfVotes(numberOfVotes);
		
		int currentRank = holiday.getRating();
		currentRank += rank;
		holiday.setRating(currentRank);
		if(numberOfVotes == 0){
			System.out.println("0000000000000000000000");
		}else{
		int avarage = currentRank / numberOfVotes;
		holiday.setAvarage(avarage);
		}
		session.update(holiday);
		session.getTransaction().commit();

	}

}
